#include <stdio.h>
#include <math.h>

int DecToBin(int num, char *report);
int DecToBin1(int num, char *report);
int clear_bit(int num, int n);
int set_bit(int num, int n);
int get_subnet(char *ip, char *sub_mask, char *subnet);
int get_num(int *num, int n, char *str);
int count_binaray_bits(int num, int n);
int main()
{
    /*
    char number[20] = {0};
    int num = 0, n = 0;
    // scanf("%d", &num);
    num = 0b11111111;
    n = 3;
    num = clear_bit(num, n);
    // num = set_bit(num, n);
    num = DecToBin(num, number);
    printf("\n");
    puts(number);
    */
    int a = 256;
    a = count_binaray_bits(a, 1);
    printf("%d\n", a);
    char ip[16] = "192.168.123.321";
    char sub_msak[16] = "255.255.255.0";
    char res[16] = {0};
    get_subnet(ip, sub_msak, res);
    puts(res);
    return 0;
}

int DecToBin(int num, char *report)
{
    int i = 0;
    int bit = 0;
    bit = num % 2;
    num = num / 2;
    if (num != 0)
    {
        i = DecToBin(num, report);
    }

    report[i] = bit + '0';
    i++;
    return i;
}

int clear_bit(int num, int n)
{
    // n = pow(2, n);
    int bit_mask = 1 << n;
    num = num & ~bit_mask;
    return num;
}

int set_bit(int num, int n)
{
    // n = pow(2, n);
    int bit_mask = 1 << n;
    num = num | bit_mask;
    return num;
}

// 4. 编写自定义函数，统计一个整数二进制位1的个数
int count_binaray_bits(int num, int n)
{
    int count = 0;
    while (num != 0)
    {
        if (num & 1 == 1)
        {
            count++;
        }
        num = num >> 1;
    }
    return count;
}
// 5. 编写函数,实现功能，输入IP地址和子网掩码，输出子网地址。
int get_subnet(char *ip, char *sub_mask, char *subnet)
{
    int sub[4] = {0};
    int submask[4] = {0};
    get_num(sub, 4, ip);
    get_num(submask, 4, sub_mask);

    sprintf(subnet, "%d.%d.%d.%d", sub[0] & submask[0], sub[1] & submask[1], sub[2] & submask[2], sub[3] & submask[3]);
}

int get_num(int *num, int n, char *str)
{
    int i = 0, j = 0;
    for (i = 0; i < n; i++)
    {
        while (str[j] != '.' && str[j] != '\0')
        {
            num[i] = num[i] * 10 + (int)(str[j] - '0');
            j++;
        }
        printf("%d ", num[i]);
        j++;
    }
    return i;
}

int DecToBin1(int num, char *report)
{
    int i = 0, j = 0, n = 0;
    char ch = '\0';
    while (num > 0)
    {
        report[i] = (num % 2) + '0';
        i++;
        num = num / 2;
    }

    n = (i - 1) / 2;
    for (j = 0; j < n; j++)
    {
        ch = report[j];
        report[j] = report[i - 1 - j];
        report[i - 1 - j] = ch;
    }
    return i;
}